<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="系统参数" name="system">
          <el-form :model="systemForm" label-width="120px">
            <el-form-item label="系统名称">
              <el-input v-model="systemForm.systemName" />
            </el-form-item>
            <el-form-item label="系统Logo">
              <el-upload class="logo-uploader" action="/api/upload" :show-file-list="false"
                :on-success="handleLogoSuccess" :before-upload="beforeLogoUpload">
                <el-image v-if="systemForm.logo" :src="systemForm.logo" class="logo" />
                <el-icon v-else class="upload-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="最大借阅数量">
              <el-input-number v-model="systemForm.maxBorrow" :min="1" :max="100" />
            </el-form-item>
            <el-form-item label="借阅期限(天)">
              <el-input-number v-model="systemForm.borrowDays" :min="1" :max="90" />
            </el-form-item>
            <el-form-item label="续借次数">
              <el-input-number v-model="systemForm.renewTimes" :min="0" :max="5" />
            </el-form-item>
            <el-form-item label="逾期罚金(元/天)">
              <el-input-number v-model="systemForm.overdueFine" :min="0" :precision="2" :step="0.1" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSystem">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="邮件设置" name="email">
          <el-form :model="emailForm" label-width="120px">
            <el-form-item label="SMTP服务器">
              <el-input v-model="emailForm.smtpServer" />
            </el-form-item>
            <el-form-item label="SMTP端口">
              <el-input v-model="emailForm.smtpPort" />
            </el-form-item>
            <el-form-item label="发件人邮箱">
              <el-input v-model="emailForm.senderEmail" />
            </el-form-item>
            <el-form-item label="发件人名称">
              <el-input v-model="emailForm.senderName" />
            </el-form-item>
            <el-form-item label="邮箱密码">
              <el-input v-model="emailForm.password" type="password" show-password />
            </el-form-item>
            <el-form-item label="启用SSL">
              <el-switch v-model="emailForm.enableSSL" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveEmail">保存设置</el-button>
              <el-button @click="handleTestEmail">发送测试邮件</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="备份管理" name="backup">
          <div class="backup-header">
            <el-button type="primary" @click="handleBackup">
              <el-icon>
                <Upload />
              </el-icon>创建备份
            </el-button>
            <div class="backup-settings">
              <span>自动备份：</span>
              <el-switch v-model="backupForm.autoBackup" @change="handleAutoBackupChange" />
              <el-select v-model="backupForm.frequency" placeholder="选择频率" :disabled="!backupForm.autoBackup">
                <el-option label="每天" value="daily" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
              </el-select>
              <el-time-picker v-model="backupForm.time" format="HH:mm" placeholder="选择时间"
                :disabled="!backupForm.autoBackup" />
            </div>
          </div>

          <el-table :data="backupList" style="width: 100%">
            <el-table-column prop="fileName" label="备份文件" />
            <el-table-column prop="size" label="文件大小" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleRestore(row)">恢复</el-button>
                <el-button type="success" link @click="handleDownload(row)">下载</el-button>
                <el-button type="danger" link @click="handleDeleteBackup(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
              :total="total" layout="total, sizes, prev, pager, next" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 备份确认对话框 -->
    <el-dialog v-model="backupDialog.visible" :title="backupDialog.title" width="400px">
      <div class="backup-progress" v-if="backupDialog.inProgress">
        <el-progress :percentage="backupDialog.progress" />
        <p>{{ backupDialog.message }}</p>
      </div>
      <div v-else>
        <p>{{ backupDialog.message }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="backupDialog.visible = false" :disabled="backupDialog.inProgress">取消</el-button>
          <el-button type="primary" @click="handleConfirmBackup" :loading="backupDialog.inProgress">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'

// 页面状态
const activeTab = ref('system')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 系统设置表单
const systemForm = ref({
  systemName: '图书管理系统',
  logo: '',
  maxBorrow: 5,
  borrowDays: 30,
  renewTimes: 1,
  overdueFine: 0.5
})

// 邮件设置表单
const emailForm = ref({
  smtpServer: 'smtp.example.com',
  smtpPort: '465',
  senderEmail: 'library@example.com',
  senderName: '图书馆管理员',
  password: '',
  enableSSL: true
})

// 备份设置表单
const backupForm = ref({
  autoBackup: false,
  frequency: 'daily',
  time: new Date(2024, 0, 1, 2, 0)
})

// 备份列表数据
const backupList = ref([
  {
    fileName: 'backup_20240215_102030.zip',
    size: '15.2MB',
    createTime: '2024-02-15 10:20:30'
  },
  {
    fileName: 'backup_20240214_102030.zip',
    size: '14.8MB',
    createTime: '2024-02-14 10:20:30'
  }
])

// 备份对话框状态
const backupDialog = ref({
  visible: false,
  title: '创建备份',
  message: '确认创建系统备份？',
  inProgress: false,
  progress: 0
})

// Logo上传处理
const handleLogoSuccess = (response) => {
  systemForm.value.logo = response.url
  ElMessage.success('Logo上传成功')
}

const beforeLogoUpload = (file) => {
  const isImage = /^image\/(jpeg|png|gif)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

// 系统设置保存
const handleSaveSystem = () => {
  ElMessage.success('系统设置保存成功')
}

// 邮件设置保存
const handleSaveEmail = () => {
  ElMessage.success('邮件设置保存成功')
}

// 发送测试邮件
const handleTestEmail = () => {
  ElMessage.success('测试邮件发送成功')
}

// 自动备份设置改变
const handleAutoBackupChange = (value) => {
  if (value) {
    ElMessage.info('已开启自动备份')
  } else {
    ElMessage.info('已关闭自动备份')
  }
}

// 创建备份
const handleBackup = () => {
  backupDialog.value.visible = true
}

// 确认备份
const handleConfirmBackup = () => {
  backupDialog.value.inProgress = true
  backupDialog.value.message = '正在创建备份...'

  // 模拟备份进度
  let progress = 0
  const timer = setInterval(() => {
    progress += 10
    backupDialog.value.progress = progress
    if (progress >= 100) {
      clearInterval(timer)
      ElMessage.success('备份创建成功')
      backupDialog.value.visible = false
      backupDialog.value.inProgress = false
      backupDialog.value.progress = 0
    }
  }, 500)
}

// 恢复备份
const handleRestore = (backup) => {
  ElMessageBox.confirm(
    `确认要恢复到备份"${backup.fileName}"吗？此操作将覆盖当前数据！`,
    '恢复确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('备份恢复成功')
  })
}

// 下载备份
const handleDownload = (backup) => {
  ElMessage.success(`开始下载${backup.fileName}`)
}

// 删除备份
const handleDeleteBackup = (backup) => {
  ElMessageBox.confirm(
    `确认要删除备份"${backup.fileName}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('备份删除成功')
  })
}
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.settings-card {
  min-height: calc(100vh - 100px);
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-uploader:hover {
  border-color: #409EFF;
}

.logo {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.backup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.backup-settings {
  display: flex;
  align-items: center;
  gap: 15px;
}

.backup-progress {
  text-align: center;
}

.backup-progress p {
  margin-top: 10px;
  color: #606266;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>